package com.hallowd.purcom;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class showCommunityActivity extends Activity {
    String communityName;
    String communityDescription;
    String communityID;
    private TextView myText = null;
    Activity activity;
    Button homeButton;
    Button joinCommunityButton;
    Button EventButton;
    Button StuffButton;
    Button ServiceButton;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_community);
        Bundle extras = getIntent().getExtras();
        new showButtonsAsyncTask().execute();
        activity = this;

        communityName = extras.getString("communityName");
        communityDescription = extras.getString("communityDescription");
        communityID = extras.getString("communityID");
        Log.d("", "community name:"+ communityName+ " community descrp:"+ communityDescription+ "communityID"+ communityID);
        TextView NameText =(TextView) findViewById(R.id.NameText);
        TextView DescriptionText =(TextView) findViewById(R.id.DescriptionText);
        NameText.setText(communityName);
        DescriptionText.setText(communityDescription);

        homeButton = (Button) findViewById(R.id.homeButton);
        homeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, wellcomePageActivity.class);
                startActivity(intent);
            }
        });
        EventButton = (Button) findViewById(R.id.EvenButton);
        EventButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, EventActivity.class);
                intent.putExtra("communityID",communityID);
                startActivity(intent);
            }
        });
        StuffButton = (Button) findViewById(R.id.StuffButton);
        StuffButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, StuffActivity.class);
                intent.putExtra("communityID",communityID);
                startActivity(intent);
            }
        });
        ServiceButton = (Button) findViewById(R.id.ServiceButton);
        ServiceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, ServiceActivity.class);
                intent.putExtra("communityID",communityID);
                startActivity(intent);
            }
        });

        joinCommunityButton = (Button) findViewById(R.id.joinCommunityButton);
        joinCommunityButton.setOnClickListener(new View.OnClickListener() {
            @Override

                public void onClick(View v) {
                    (new showCommunityAsyncTask()).execute();
                }


        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_show_community, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    private class showCommunityAsyncTask extends AsyncTask<String, Integer, String> {
    @Override
        protected String doInBackground(String... params) {

           String url = "http://titan.cmpe.boun.edu.tr:8089/purcom/mobile/community/" + communityID + "/join";
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost request = new HttpPost(url);
            request.addHeader("Content-Type", "application/json");
            request.addHeader("Accept", "application/json");
            Long userId = null;
            SharedPreferences pref = getApplicationContext().getSharedPreferences("purcomPref", MODE_PRIVATE);
            userId = pref.getLong("userID",-1L);

            try {
                JSONArray join = new JSONArray();

                String s = String.valueOf(userId);

                 StringEntity se = new StringEntity(s);

                 request.setEntity(se);

                 HttpResponse response = httpclient.execute(request);

                 if (response.getStatusLine().getStatusCode() == 200) {
                     BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

                    StringBuilder builder = new StringBuilder();
                    for (String line = null; (line = reader.readLine()) != null; ) {
                        builder.append(line).append("\n");
                    }

                    Log.d("", "Join Community " + builder.toString());
                    return builder.toString();
                 } else
                    Log.d("", "join Failed");
             } catch (Exception e) {
                Log.d("", e.toString());
                Log.d("", "Connection problem occured");
             }
            return null;
        }

    }

    private class showButtonsAsyncTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            Long userId = null;
            SharedPreferences pref = getApplicationContext().getSharedPreferences("purcomPref", MODE_PRIVATE);
            userId = pref.getLong("userID",-1L);
            String url = "http://titan.cmpe.boun.edu.tr:8089/purcom/mobile/community/"+communityID+"/getMembership?userId="+userId;
            HttpClient httpclient = new DefaultHttpClient();
            HttpUriRequest request = new HttpGet(url);

            try {
                HttpResponse response = httpclient.execute(request);
                if (response.getStatusLine().getStatusCode() == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

                    StringBuilder builder = new StringBuilder();
                    for (String line = null; (line = reader.readLine()) != null; ) {
                        builder.append(line).append("\n");
                    }

                    Log.d("", "Show Button Result "+builder.toString());
                    String deneme = builder.toString();
                    try{
                        JSONObject jObj = new JSONObject(deneme);
                        Integer x = jObj.length();

                        Log.d("", "Json Parse isMember = " +x);
                        if(x == 2){
                            Button EventButton =(Button)findViewById(R.id.EvenButton);
                            EventButton.setVisibility(0); //To set visible

                            Button ServiceButton =(Button)findViewById(R.id.ServiceButton);
                            ServiceButton.setVisibility(0); //To set visible

                            Button StuffButton =(Button)findViewById(R.id.StuffButton);
                            StuffButton.setVisibility(0); //To set visible

                        }else{
                            Button joinCommunityButton =(Button)findViewById(R.id.joinCommunityButton);
                            joinCommunityButton.setVisibility(0); //To set visible
                        }
                    }catch(Exception ex){
                        Log.d("", "Json Parse catched");
                        return "FALSE";
                    }

                    return builder.toString();
                }
                else
                    Log.d("", "Show Button Result Failed");
            } catch (IOException e) {
                Log.d("", "Connection problem occured");
            }
            return null;
        }

        protected void onPostExecute(String result) {

            if(result == null){
                AlertDialog.Builder builder = new AlertDialog.Builder(showCommunityActivity.this);
                builder.setMessage("Show Button Result failed.")
                        .setTitle("Result")
                        .setPositiveButton(android.R.string.ok, null);
                AlertDialog dialog = builder.create();
                dialog.show();
                return;
            }else{
                try{
                   /* */

                }catch(Exception ex){
                    AlertDialog.Builder builder = new AlertDialog.Builder(showCommunityActivity.this);
                    builder.setMessage("Login failed.")
                            .setTitle("Result")
                            .setPositiveButton(android.R.string.ok, null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                    return;
                }
            }





            Log.i("Show Button Result successful", result);



        }
    }
}

